#include "TimeUtil.h"

#include <chrono>
#include <ctime>
#include <iomanip>
#include <sstream>

std::string format_time(const std::chrono::system_clock::time_point& tp) {
    auto tt = std::chrono::system_clock::to_time_t(tp);
    std::stringstream ss;

    std::tm tm_snapshot;
#if defined(_WIN32)
    localtime_s(&tm_snapshot, &tt);
#else
    localtime_r(&tt, &tm_snapshot);
#endif

    ss << std::put_time(&tm_snapshot, "[%Y-%m-%d %H:%M:%S");

    // 提取毫秒部分
    auto duration = tp.time_since_epoch();
    auto ms = std::chrono::duration_cast<std::chrono::milliseconds>(duration) % 1000;
    ss << "." << std::setfill('0') << std::setw(3) << ms.count() << "]";
    return ss.str();
}

std::string format_with_second(std::time_t secTimestamp) {
    auto tp = std::chrono::system_clock::from_time_t(secTimestamp);
    return format_time(tp);
}

std::string format_with_milliseconds(int64_t millsTimestamp) {
    auto tp = std::chrono::system_clock::time_point(std::chrono::milliseconds(millsTimestamp));
    return format_time(tp);
}

std::string get_time() {
    return format_time(std::chrono::system_clock::now());
}

int64_t get_timestamp_for_second() {
    return std::chrono::duration_cast<std::chrono::seconds>(
            std::chrono::system_clock::now().time_since_epoch())
            .count();
}

int64_t get_timestamp_for_millisecond() {
    return std::chrono::duration_cast<std::chrono::milliseconds>(
            std::chrono::system_clock::now().time_since_epoch())
            .count();
}